package cn.zxh.improvement.auth.security.authentication.admin.password;

import org.springframework.context.ApplicationContext;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

public class AdminPasswordConfigurer extends AbstractHttpConfigurer<AdminPasswordConfigurer, HttpSecurity> {
    @Override
    public void init(HttpSecurity builder) throws Exception {
        super.init(builder);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        ApplicationContext applicationContext = http.getSharedObject(ApplicationContext.class);

        AuthenticationManagerBuilder builder = http.getSharedObject(AuthenticationManagerBuilder.class);
        AdminPasswordLoginProcessFilter passwordLoginProcessFilter = new AdminPasswordLoginProcessFilter(builder.getObject());
        AuthenticationSuccessHandler successHandler = applicationContext.getBean(AuthenticationSuccessHandler.class);
        AuthenticationFailureHandler failureHandler = applicationContext.getBean(AuthenticationFailureHandler.class);

        passwordLoginProcessFilter.setAuthenticationSuccessHandler(successHandler);
        passwordLoginProcessFilter.setAuthenticationFailureHandler(failureHandler);

        http.addFilterBefore(passwordLoginProcessFilter, UsernamePasswordAuthenticationFilter.class);
        super.configure(http);
    }

    public static AdminPasswordConfigurer adminPassLogin() {
        return new AdminPasswordConfigurer();
    }

}
